<template>
  <div>
    <el-container>
      <el-header style="height:auto;">
        <el-switch
          v-model="enable"
          active-color="#13ce66"
          inactive-color="#ff4949"
          title="状态过滤"
        />
        <el-select v-model="agency">
          <el-option label="所有" value="all" />
          <el-option
            v-for="item in ads_agencies"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="kwInput" placeholder="输入广告ID搜索" style="max-width: 600px" clearable class="" @keyup.native.enter="handleSearch">
          <el-button slot="append" style="width: 180px" type="success" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button type="success" @click="googleReportConfigVisual=true">报告配置</el-button>
        <el-button type="primary" @click="RechargeSumVisual=true">充值统计</el-button>
      </el-header>
      <el-main>
        <el-table
          ref="budgettable"
          v-loading="listLoading"
          :data="data.filter(item => !kwInput || item.domain.toLowerCase().includes(kwInput.toLowerCase()) ||item.ad.toLowerCase().includes(kwInput.toLowerCase()))"
          border
          height="750"
          :default-sort="{prop: 'budget_remaining', order: 'descending'}"
          show-summary
          @sort-change="handleSort"
        >
          <el-table-column align="center" prop="domain" label="网站" sortable="custom" width="300">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                title="信息"
                width="400"
                trigger="click"
              >
                <el-row>
                  <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <p>经理账号:{{ scope.row.manager }}</p><br>
                    <p>广告 ID:{{ scope.row.ad }}</p>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <p>mc服务器:{{ scope.row.api_url }}</p>
                  </el-col>
                </el-row>

                <div>[备注]{{ scope.row.note }}</div>
                <hr>
                <span slot="reference">{{ scope.row.domain }}</span>
              </el-popover>
              <br>
              <span>{{ scope.row.ad }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column align="center" prop="ad" label="广告ID" sortable="custom">-->
          <!--            <template  slot-scope="scope">-->
          <!--               <el-popover-->
          <!--                placement="top-start"-->
          <!--                title="账号信息"-->
          <!--                width="600"-->
          <!--                trigger="click"-->
          <!--              >-->
          <!--                <div>-->
          <!--                  <el-row>-->
          <!--                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">-->
          <!--                      <p>经理账号:{{scope.row.manager}}</p>-->
          <!--                      <p>广告 ID:{{scope.row.ad}}</p>-->
          <!--                    </el-col>-->
          <!--                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">-->
          <!--                      <p>mc服务器:{{scope.row.api_url}}</p>-->
          <!--                    </el-col>-->
          <!--                  </el-row>-->
          <!--                </div>-->
          <!--                <span slot="reference">{{scope.row.ad}}</span>-->
          <!--              </el-popover>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column align="center" label="最后充值" width="120" prop="update_at" sortable="custom">
            <template slot-scope="scope">
              <span style="display: block">{{ scope.row.last_charge }}</span>
              <span>{{ scope.row.update_at }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="剩余预算" width="120" prop="budget_remaining" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.cost !== ''">
                <el-tag v-if="scope.row.budget_remaining <= (scope.row.cost)" type="danger" size="mini">
                  {{ scope.row.budget_remaining }}
                </el-tag>
                <el-tag v-else-if="scope.row.budget_remaining <= (scope.row.cost*3) " type="warning" size="mini">
                  {{ scope.row.budget_remaining }}
                </el-tag>
                <span v-else>{{ scope.row.budget_remaining }}</span>
              </div>
              <div v-else>
                <el-tag v-if="scope.row.budget_remaining <= (scope.row.cost)" type="danger" size="mini">
                  {{ scope.row.budget_remaining }}
                </el-tag>
                <el-tag v-else-if="scope.row.budget_remaining <= (scope.row.cost*3) " type="warning" size="mini">
                  {{ scope.row.budget_remaining }}
                </el-tag>
                <span v-else>{{ scope.row.budget_remaining }}</span>
              </div>

            </template>
          </el-table-column>
          <el-table-column align="center" label="每日预算" width="120" prop="total_daily_budget" sortable="custom" />
          <el-table-column align="center" label="总预算" width="120" prop="budget_amount" sortable="custom" />
          <!--<el-table-column align="center" label="百分比" prop="budget_spent" sortable="custom">-->
          <!--<template slot-scope="scope">-->
          <!--{{(scope.row.budget_spent*100).toFixed(0)}}%-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column align="center" label="currency" prop="budget_currency">-->
          <!--</el-table-column>-->
          <el-table-column align="center" label="昨日消耗" width="120" prop="cost" sortable="custom" />
          <el-table-column align="center" label="昨日收入" width="120" prop="amount" sortable="custom" />
          <el-table-column align="center" label="ROI" width="100" prop="roi" sortable="custom" />
          <el-table-column align="center" label="状态" prop="enable" sortable="custom">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                size="mini"
                style="display: inline-block;float: left"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
              <el-select v-model="scope.row.agency" size="mini" placeholder="代理" clearable style="display: inline-block;float: left;width: 150px;margin-right: 5px;">
                <el-option
                  v-for="item in ads_agencies"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-popconfirm
                style="display: inline-block;float: left;"
                size="mini"
                title="确定修改吗？"
                @confirm="handleModify(scope.row)"
              >
                <el-button slot="reference" size="mini" type="success" icon="el-icon-check" circle />
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-dropdown>
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native.stop="handleAdwords(scope.row)">充值</el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleShowGoogleMerchant(scope.row)">MC账号</el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleSync(scope.row)">更新报告文件</el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleAction('edit', scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click.native.stop="handleAction('delete', scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-dialog
          append-to-body
          :title="title"
          :width="width"
          :visible.sync="innerDialogVisible"
          :close-on-click-modal="false"
        >
          <el-form :model="temp" label-position="left" label-width="120px">
            <el-form-item v-if="action !== 'delete'" label="statue:">
              <el-input v-model="temp.status" />
            </el-form-item>
            <el-form-item v-if="action !== 'delete'" label="备注:">
              <el-input v-model="temp.note" />
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="innerDialogVisible = false">取 消</el-button>
            <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
          </span>
        </el-dialog>
      </el-main>

    </el-container>
    <adwordsrecharges
      :show-dialog="adwordsrechargesVisuable"
      :website_id="current_website_id"
      :ads_id="current_ads_id"
      :domain="current_website_domain"
      @closeMyDialog="adwordsrechargesVisuable=false"
    />
    <merchant :merchant-visible="merchantVisible" :website_id="current_website_id" @closeMerchantDialog="merchantVisible=false" />
    <googleadsreportconfig
      :d-visible="googleReportConfigVisual"
      @closeMyDialog="googleReportConfigVisual=false"
    />
    <rechargessum :show-dialog="RechargeSumVisual" @closeMyDialog="RechargeSumVisual=false" />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/orders/googleadsbudget'
import { Sync } from '@/api/orders/googleadsreportconfig'
import Googleadsreportconfig from './element/googleadsreportconfig'
import merchant from '@/views/orders/element/merchant'
import Adwordsrecharges from './element/adwordsrecharges'
import qs from 'qs'
import Rechargessum from './element/rechargessum'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  components: { Rechargessum, Adwordsrecharges, merchant, Googleadsreportconfig },
  data() {
    return {
      current_website_id: '',
      current_ads_id: '',
      adwordsrechargesVisuable: false,
      current_website_domain: '',
      merchantVisible: false,
      googleReportConfigVisual: false,
      RechargeSumVisual: false,
      processLoading: false,
      feedproductVisual: false,
      addfeedDialogVisual: false,
      syncloading: false,
      fetchloading: false,
      data: [],
      title: 'Google 广告预算',
      listLoading: false,
      kwInput: '',
      agency: 'all',
      enable: true,
      order_by: 'budget_remaining',
      order_desc: 0,
      // pagination
      pagesize: 50,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      ads_agencies: [
        {
          label: '未设置',
          value: ''
        },
        {
          label: '自己注册',
          value: 'byself'
        },
        {
          label: '易赛诺',
          value: 'yisainuo'
        },
        {
          label: '飞书互动',
          value: 'sinoclick'
        }
      ],
      temp: {
        status: '',
        note: '',
        ad: '',
        id: ''
      },
      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        file_url: '',
        website_id: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        agency: this.agency,
        enable: this.enable,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAdwords(row) {
      if (row.website_id === '') {
        this.$notify({
          title: '提示',
          message: '没有匹配的网站',
          type: 'info',
          duration: 2000
        })
        return
      }
      this.adwordsrechargesVisuable = true
      this.current_website_id = row.website_id
      this.current_ads_id = row.ad
      this.current_website_domain = row.domain
    },
    handleShowGoogleMerchant(row) {
      this.current_website_id = row.website_id
      this.merchantVisible = true
    },
    handleSync(row) {
      if (row.googleadsreportconfig_id === '') {
        this.notify('config id为空')
        return
      }
      this.listLoading = true
      Sync({
        id: row.googleadsreportconfig_id
      }
      ).then(response => {
        this.notify('处理成功')
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.ad}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改广告${row.ad} ${row.domain}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'add':
          this.width = '50%'
          this.title = `增加`
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'add':
          this.listLoading = true
          Post({
            ad: _data.ad
          }
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
            this.listLoading = false
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
        case 'delete' :
          this.listLoading = true
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
        case 'edit':
          this.listLoading = true
          Put(_data.id, {
            status: _data.status,
            note: _data.note,
            id: _data.id
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
      }
    },
    handleModify(row) {
      Put(row.id, {
        enable: row.enable,
        agency: row.agency,
        id: row.id
      }).then((response) => {
        this.getList()
        this.notify('更新成功')
      }).catch(err => {
        console.log(err)
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
  .app-container >>> table, tr {
    border-color: black;
  }

  .el-header {
    height: 120px;
    margin-top: 10px;
  }

  .el-header, .el-footer {
    color: white;
  }

  .el-container >>> .pointer {
    cursor: pointer;
    color: #409EFF;
  }

  .el-container >>> a:visited {
    color: purple;
  }

  .el-container >>> a:link {
    color: #409EFF;
  }

  .el-container >>> a:active {
    color: red;
  }

  .app-container >>> a:hover {
    color: red;
    text-decoration: underline;
  }
</style>
